package com.example.smartagrisys.controller;

import com.example.smartagrisys.common.Result;
import com.example.smartagrisys.dto.ComplaintDTO;
import com.example.smartagrisys.dto.ReplyDTO;
import com.example.smartagrisys.service.ComplaintService;
import com.example.smartagrisys.util.SecurityUtil;
import com.example.smartagrisys.util.RoleUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 投诉控制器
 */
@Slf4j
@RestController
@RequestMapping("/complaint")
public class ComplaintController {
    
    @Autowired
    private ComplaintService complaintService;
    
    /**
     * 获取当前用户的投诉列表
     *
     * @return 投诉列表
     */
    @GetMapping("/my")
    public Result<List<ComplaintDTO>> getMyComplaints() {
        Long userId = SecurityUtil.getCurrentUserId();
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        String role = SecurityUtil.getCurrentUserRole();
        List<ComplaintDTO> complaints;
        
        if (RoleUtil.isBuyer(role)) {
            log.info("获取买家(ID:{})的投诉列表", userId);
            complaints = complaintService.getBuyerComplaints(userId);
        } else if (RoleUtil.isSellerOrFarmer(role)) {
            log.info("获取卖家(ID:{})的投诉列表", userId);
            complaints = complaintService.getSellerComplaints(userId);
        } else {
            return Result.error("无权限访问");
        }
        
        return Result.success(complaints);
    }
    
    /**
     * 获取投诉详情
     *
     * @param id 投诉ID
     * @return 投诉详情
     */
    @GetMapping("/{id}")
    public Result<ComplaintDTO> getComplaintById(@PathVariable("id") Long id) {
        Long userId = SecurityUtil.getCurrentUserId();
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        ComplaintDTO complaint = complaintService.getComplaintById(id);
        if (complaint == null) {
            return Result.error("投诉不存在");
        }
        
        // 验证权限
        if (!complaint.getBuyerId().equals(userId) && !complaint.getFarmerId().equals(userId)) {
            return Result.error("无权查看该投诉");
        }
        
        return Result.success(complaint);
    }
    
    /**
     * 创建投诉
     *
     * @param complaintDTO 投诉信息
     * @return 创建结果
     */
    @PostMapping
    public Result<ComplaintDTO> createComplaint(@RequestBody ComplaintDTO complaintDTO) {
        Long buyerId = SecurityUtil.getCurrentUserId();
        if (buyerId == null) {
            return Result.error("用户未登录");
        }
        
        String role = SecurityUtil.getCurrentUserRole();
        if (!RoleUtil.isBuyer(role)) {
            return Result.error("只有买家可以提交投诉");
        }
        
        // 设置买家ID
        complaintDTO.setBuyerId(buyerId);
        
        try {
            ComplaintDTO created = complaintService.createComplaint(complaintDTO);
            return Result.success(created);
        } catch (Exception e) {
            log.error("创建投诉失败", e);
            return Result.error("创建投诉失败: " + e.getMessage());
        }
    }
    
    /**
     * 回复投诉
     *
     * @param id           投诉ID
     * @param requestBody  回复内容
     * @return 回复结果
     */
    @PutMapping("/{id}/reply")
    public Result<Boolean> replyComplaint(
            @PathVariable("id") Long id,
            @RequestBody Map<String, String> requestBody) {
        
        Long sellerId = SecurityUtil.getCurrentUserId();
        if (sellerId == null) {
            return Result.error("用户未登录");
        }
        
        String role = SecurityUtil.getCurrentUserRole();
        if (!"ROLE_SELLER".equals(role) && !"ROLE_FARMER".equals(role)) {
            return Result.error("只有卖家可以回复投诉");
        }
        
        ComplaintDTO complaint = complaintService.getComplaintById(id);
        if (complaint == null) {
            return Result.error("投诉不存在");
        }
        
        // 验证是否是本人的投诉
        if (!complaint.getFarmerId().equals(sellerId)) {
            return Result.error("不能回复不属于自己的投诉");
        }
        
        String replyContent = requestBody.get("content");
        if (replyContent == null || replyContent.trim().isEmpty()) {
            return Result.error("回复内容不能为空");
        }
        
        log.info("卖家(ID:{})回复投诉(ID:{})", sellerId, id);
        boolean success = complaintService.replyComplaint(id, replyContent);
        
        if (!success) {
            return Result.error("回复投诉失败");
        }
        
        return Result.success(true);
    }
    
    /**
     * 解决投诉
     *
     * @param id           投诉ID
     * @param requestBody  解决方案
     * @return 解决结果
     */
    @PutMapping("/{id}/resolve")
    public Result<Boolean> resolveComplaint(
            @PathVariable("id") Long id,
            @RequestBody Map<String, String> requestBody) {
        
        Long sellerId = SecurityUtil.getCurrentUserId();
        if (sellerId == null) {
            return Result.error("用户未登录");
        }
        
        String role = SecurityUtil.getCurrentUserRole();
        if (!"ROLE_SELLER".equals(role) && !"ROLE_FARMER".equals(role)) {
            return Result.error("只有卖家可以解决投诉");
        }
        
        ComplaintDTO complaint = complaintService.getComplaintById(id);
        if (complaint == null) {
            return Result.error("投诉不存在");
        }
        
        // 验证是否是本人的投诉
        if (!complaint.getFarmerId().equals(sellerId)) {
            return Result.error("不能解决不属于自己的投诉");
        }
        
        String solution = requestBody.get("solution");
        if (solution == null || solution.trim().isEmpty()) {
            return Result.error("解决方案不能为空");
        }
        
        log.info("卖家(ID:{})解决投诉(ID:{})", sellerId, id);
        boolean success = complaintService.resolveComplaint(id, solution);
        
        if (!success) {
            return Result.error("解决投诉失败");
        }
        
        return Result.success(true);
    }
    
    /**
     * 关闭投诉
     *
     * @param id 投诉ID
     * @return 关闭结果
     */
    @PutMapping("/{id}/close")
    public Result<Boolean> closeComplaint(@PathVariable("id") Long id) {
        Long buyerId = SecurityUtil.getCurrentUserId();
        if (buyerId == null) {
            return Result.error("用户未登录");
        }
        
        String role = SecurityUtil.getCurrentUserRole();
        if (!RoleUtil.isBuyer(role)) {
            return Result.error("只有买家可以关闭投诉");
        }
        
        // 验证投诉是否属于当前买家
        ComplaintDTO complaint = complaintService.getComplaintById(id);
        if (complaint == null) {
            return Result.error("投诉不存在");
        }
        
        if (!complaint.getBuyerId().equals(buyerId)) {
            return Result.error("无权操作此投诉");
        }
        
        boolean success = complaintService.closeComplaint(id);
        if (success) {
            return Result.success(true);
        } else {
            return Result.error("关闭投诉失败");
        }
    }
    
    /**
     * 买家跟进投诉
     *
     * @param id 投诉ID
     * @param replyDTO 跟进内容
     * @return 跟进结果
     */
    @PutMapping("/{id}/followup")
    public Result<Boolean> followUpComplaint(@PathVariable("id") Long id, @RequestBody ReplyDTO replyDTO) {
        Long buyerId = SecurityUtil.getCurrentUserId();
        if (buyerId == null) {
            return Result.error("用户未登录");
        }
        
        String role = SecurityUtil.getCurrentUserRole();
        if (!RoleUtil.isBuyer(role)) {
            return Result.error("只有买家可以跟进投诉");
        }
        
        // 验证投诉是否属于当前买家
        ComplaintDTO complaint = complaintService.getComplaintById(id);
        if (complaint == null) {
            return Result.error("投诉不存在");
        }
        
        if (!complaint.getBuyerId().equals(buyerId)) {
            return Result.error("无权操作此投诉");
        }
        
        boolean success = complaintService.followUpComplaint(id, replyDTO.getContent());
        if (success) {
            return Result.success(true);
        } else {
            return Result.error("跟进投诉失败");
        }
    }
} 